// go:build ignore
//go:build ignore
// +build ignore

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strings"
)

// JSONRPCRequest JSON-RPC 请求结构
type JSONRPCRequest struct {
	JSONRPC string      `json:"jsonrpc"`
	ID      interface{} `json:"id"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params,omitempty"`
}

// JSONRPCResponse JSON-RPC 响应结构
type JSONRPCResponse struct {
	JSONRPC string        `json:"jsonrpc"`
	ID      interface{}   `json:"id"`
	Result  interface{}   `json:"result,omitempty"`
	Error   *JSONRPCError `json:"error,omitempty"`
}

// JSONRPCError JSON-RPC 错误结构
type JSONRPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// testMCPProtocol 测试 MCP 协议
func testMCPProtocol() {
	fmt.Println("=== MCP 协议测试工具 ===")
	fmt.Println("这个工具可以帮助您测试和调试 MySQL MCP 服务器")
	fmt.Println()

	tests := []struct {
		name    string
		request JSONRPCRequest
	}{
		{
			name: "初始化请求",
			request: JSONRPCRequest{
				JSONRPC: "2.0",
				ID:      1,
				Method:  "initialize",
				Params: map[string]interface{}{
					"protocolVersion": "2024-11-05",
					"capabilities": map[string]interface{}{
						"tools": map[string]interface{}{},
					},
					"clientInfo": map[string]interface{}{
						"name":    "test-client",
						"version": "1.0.0",
					},
				},
			},
		},
		{
			name: "列出工具",
			request: JSONRPCRequest{
				JSONRPC: "2.0",
				ID:      2,
				Method:  "tools/list",
			},
		},
		{
			name: "Ping 测试",
			request: JSONRPCRequest{
				JSONRPC: "2.0",
				ID:      3,
				Method:  "tools/call",
				Params: map[string]interface{}{
					"name":      "ping",
					"arguments": map[string]interface{}{},
				},
			},
		},
		{
			name: "列出表",
			request: JSONRPCRequest{
				JSONRPC: "2.0",
				ID:      4,
				Method:  "tools/call",
				Params: map[string]interface{}{
					"name":      "list_tables",
					"arguments": map[string]interface{}{},
				},
			},
		},
		{
			name: "无效 JSON 测试",
			request: JSONRPCRequest{
				JSONRPC: "invalid",
				ID:      5,
				Method:  "invalid_method",
			},
		},
	}

	fmt.Println("准备发送以下测试请求：")
	for i, test := range tests {
		fmt.Printf("%d. %s\n", i+1, test.name)
	}
	fmt.Println()

	// 生成测试用的 JSON 消息
	for i, test := range tests {
		fmt.Printf("=== 测试 %d: %s ===\n", i+1, test.name)

		jsonData, err := json.MarshalIndent(test.request, "", "  ")
		if err != nil {
			fmt.Printf("错误：无法序列化 JSON: %v\n", err)
			continue
		}

		fmt.Println("请求 JSON:")
		fmt.Println(string(jsonData))
		fmt.Println()

		// 验证 JSON 格式
		var testParse interface{}
		if err := json.Unmarshal(jsonData, &testParse); err != nil {
			fmt.Printf("❌ JSON 格式错误: %v\n", err)
		} else {
			fmt.Println("✅ JSON 格式有效")
		}

		fmt.Println(strings.Repeat("-", 50))
	}
}

// validateJSON 验证 JSON 字符串
func validateJSON(jsonStr string) error {
	var temp interface{}
	return json.Unmarshal([]byte(jsonStr), &temp)
}

// interactiveTest 交互式测试
func interactiveTest() {
	fmt.Println("=== 交互式 JSON-RPC 测试 ===")
	fmt.Println("输入 JSON-RPC 消息进行测试，输入 'quit' 退出")
	fmt.Println()

	scanner := bufio.NewScanner(os.Stdin)

	for {
		fmt.Print("输入 JSON-RPC 消息: ")
		if !scanner.Scan() {
			break
		}

		input := strings.TrimSpace(scanner.Text())
		if input == "quit" {
			break
		}

		if input == "" {
			continue
		}

		// 验证 JSON 格式
		if err := validateJSON(input); err != nil {
			fmt.Printf("❌ JSON 格式错误: %v\n", err)
			fmt.Println("错误详情：")
			fmt.Printf("  输入: %s\n", input)
			fmt.Printf("  长度: %d 字符\n", len(input))
			fmt.Println()
			continue
		}

		// 解析为 JSON-RPC 请求
		var request JSONRPCRequest
		if err := json.Unmarshal([]byte(input), &request); err != nil {
			fmt.Printf("❌ JSON-RPC 解析错误: %v\n", err)
		} else {
			fmt.Println("✅ JSON-RPC 格式有效")
			fmt.Printf("  版本: %s\n", request.JSONRPC)
			fmt.Printf("  ID: %v\n", request.ID)
			fmt.Printf("  方法: %s\n", request.Method)
			if request.Params != nil {
				paramsJSON, _ := json.MarshalIndent(request.Params, "  ", "  ")
				fmt.Printf("  参数: %s\n", string(paramsJSON))
			}
		}
		fmt.Println()
	}
}

// generateSampleConfig 生成示例配置
func generateSampleConfig() {
	fmt.Println("=== 生成示例配置 ===")

	config := map[string]interface{}{
		"mcpServers": map[string]interface{}{
			"mysql-debug": map[string]interface{}{
				"command": "./mysql-mcp-server",
				"args":    []string{"debug"},
				"env": map[string]string{
					"MYSQL_HOST":     "localhost",
					"MYSQL_PORT":     "3306",
					"MYSQL_USER":     "root",
					"MYSQL_PASSWORD": "12345678",
					"MYSQL_DATABASE": "test",
				},
			},
		},
	}

	configJSON, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		fmt.Printf("错误：无法生成配置: %v\n", err)
		return
	}

	fmt.Println("Claude Desktop 配置文件示例 (claude_desktop_config.json):")
	fmt.Println(string(configJSON))
	fmt.Println()

	// 写入文件
	if err := os.WriteFile("claude_desktop_config.json", configJSON, 0644); err == nil {
		fmt.Println("✅ 配置已保存到 claude_desktop_config.json")
	} else {
		fmt.Printf("❌ 无法保存配置文件: %v\n", err)
	}
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("用法: go run test_mcp.go <command>")
		fmt.Println("命令:")
		fmt.Println("  protocol    - 测试 MCP 协议消息")
		fmt.Println("  interactive - 交互式 JSON-RPC 测试")
		fmt.Println("  config      - 生成示例配置文件")
		return
	}

	command := os.Args[1]

	switch command {
	case "protocol":
		testMCPProtocol()
	case "interactive":
		interactiveTest()
	case "config":
		generateSampleConfig()
	default:
		log.Fatalf("未知命令: %s", command)
	}
}

/**
{"jsonrpc": "2.0","id": 2,"method": "tools/list"}
{"jsonrpc": "2.0",  "id": 4,  "method": "tools/call",  "params": {    "arguments": {},    "name": "list_tables"  }}
{"jsonrpc": "2.0",  "id": 4,  "method": "tools/call",  "params": {  "arguments": {    "query": "SELECT * FROM zkusers LIMIT 1"  },    "name": "execute_query"  }}
*/
